package net.wanho.util;

import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;

import java.util.concurrent.TimeUnit;

/**
 * 分布式锁工具类
 */
public class LockUtil {

    private static StringRedisTemplate redisTemplate = ApplicationContextHolder.getBean(StringRedisTemplate.class);

    // 获取锁的超时时间（自旋重试时间）
    private static long waitTimeout = 10000L;

    // 锁的过期时间，防止死锁
    private static long lockTimeout = 10L;

    /**
     * 获取分布式锁
     */
    public static boolean getLock(String lockName, String value){
        // 计算获取锁的超时时间
        long endTime = System.currentTimeMillis() + waitTimeout;
        // 超时之前尝试获取锁
        while(System.currentTimeMillis() < endTime){
            // 判断是否能够获取锁，其实就是判断能否往redis中插入对应的key
            Boolean flag = redisTemplate.opsForValue().setIfAbsent(lockName, value, lockTimeout, TimeUnit.SECONDS);
            if (flag){
                return true;
            }
        }
        return false;
    }

    /**
     * 释放分布式锁
     */
    public static void unlock(String lockName, String value){
        if(value.equals(redisTemplate.opsForValue().get(lockName))){
            redisTemplate.delete(lockName);
        }
    }
}